import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'kite_moment_entity.dart';
import 'kite_moment_comment_entity.dart';
import '../person/persona_session_controller.dart';

/// 风筝时刻控制器
class KiteMomentController {
  static final KiteMomentController _instance = KiteMomentController._();
  static KiteMomentController get globalInstance => _instance;

  KiteMomentController._() {
    _momentList.addAll(KiteMomentEntity.getAllPredefinedMoments());
    _commentList.addAll(KiteMomentCommentEntity.getAllPredefinedComments());
  }

  /// 风筝时刻数据列表
  final List<KiteMomentEntity> _momentList = [];

  /// 评论数据列表
  final List<KiteMomentCommentEntity> _commentList = [];

  /// 当前选中的风筝时刻
  final ReactiveValueNotifier<KiteMomentEntity?> _currentMoment =
      ReactiveValueNotifier<KiteMomentEntity?>(null);

  /// 所有风筝时刻列表状态
  final ReactiveValueNotifier<List<KiteMomentEntity>> _allMoments =
      ReactiveValueNotifier<List<KiteMomentEntity>>([]);

  /// 当前用户的风筝时刻列表状态
  final ReactiveValueNotifier<List<KiteMomentEntity>> _userMoments =
      ReactiveValueNotifier<List<KiteMomentEntity>>([]);

  /// 当前风筝时刻的评论列表状态
  final ReactiveValueNotifier<List<KiteMomentCommentEntity>> _currentComments =
      ReactiveValueNotifier<List<KiteMomentCommentEntity>>([]);

  ReactiveValueNotifier<KiteMomentEntity?> get currentMomentState =>
      _currentMoment;
  ReactiveValueNotifier<List<KiteMomentEntity>> get allMomentsState =>
      _allMoments;
  ReactiveValueNotifier<List<KiteMomentEntity>> get userMomentsState =>
      _userMoments;
  ReactiveValueNotifier<List<KiteMomentCommentEntity>>
  get currentCommentsState => _currentComments;

  /// 发布风筝时刻
  bool publishKiteMoment({
    required String title,
    required String content,
    required String authorId,
    required MediaType mediaType,
    required String mediaUrl,
    String? thumbnailUrl,
  }) {
    try {
      final newMoment = KiteMomentEntity(
        uniqueIdentifier: 'moment_${DateTime.now().millisecondsSinceEpoch}',
        momentTitle: title,
        contentText: content,
        authorIdentifier: authorId,
        mediaType: mediaType,
        mediaResourceUrl: mediaUrl,
        thumbnailResourceUrl: thumbnailUrl,
        publishTimestamp: DateTime.now(),
        commentCount: 0,
      );

      _momentList.insert(0, newMoment); // 插入到列表开头
      _refreshAllMoments();
      _refreshUserMoments(); // 刷新用户风筝时刻列表
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 查询所有风筝时刻
  List<KiteMomentEntity> getAllKiteMoments() {
    final sortedMoments = List<KiteMomentEntity>.from(_momentList);
    sortedMoments.sort(
      (a, b) => b.publishTimestamp.compareTo(a.publishTimestamp),
    );
    _allMoments.value = sortedMoments;
    return sortedMoments;
  }

  /// 查看单个风筝时刻
  KiteMomentEntity? getKiteMomentById(String momentId) {
    try {
      final moment = _momentList.firstWhere(
        (m) => m.uniqueIdentifier == momentId,
      );
      _currentMoment.value = moment;
      _loadCommentsForMoment(momentId);
      return moment;
    } catch (e) {
      return null;
    }
  }

  /// 查看指定用户发布的风筝时刻
  List<KiteMomentEntity> getUserKiteMoments(String userId) {
    final userMoments =
        _momentList
            .where((moment) => moment.authorIdentifier == userId)
            .toList();
    userMoments.sort(
      (a, b) => b.publishTimestamp.compareTo(a.publishTimestamp),
    );

    // 更新用户风筝时刻状态
    _userMoments.value = userMoments;

    return userMoments;
  }

  /// 删除风筝时刻
  bool deleteKiteMoment(String momentId) {
    try {
      final index = _momentList.indexWhere(
        (moment) => moment.uniqueIdentifier == momentId,
      );
      if (index != -1) {
        _momentList.removeAt(index);

        // 同时删除相关评论
        _commentList.removeWhere(
          (comment) => comment.momentIdentifier == momentId,
        );

        // 如果删除的是当前选中的时刻，清空当前状态
        if (_currentMoment.value?.uniqueIdentifier == momentId) {
          _currentMoment.value = null;
          _currentComments.value = [];
        }

        _refreshAllMoments();
        _refreshUserMoments(); // 刷新用户风筝时刻列表
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 发表评论
  bool addComment({
    required String momentId,
    required String authorId,
    required String content,
  }) {
    try {
      final newComment = KiteMomentCommentEntity(
        uniqueIdentifier: 'comment_${DateTime.now().millisecondsSinceEpoch}',
        momentIdentifier: momentId,
        authorIdentifier: authorId,
        commentContent: content,
        publishTimestamp: DateTime.now(),
      );

      _commentList.add(newComment);

      // 更新风筝时刻的评论数量
      final momentIndex = _momentList.indexWhere(
        (moment) => moment.uniqueIdentifier == momentId,
      );
      if (momentIndex != -1) {
        final updatedMoment = _momentList[momentIndex]
            .duplicateWithModifications(
              commentCount: _momentList[momentIndex].commentCount + 1,
            );
        _momentList[momentIndex] = updatedMoment;

        // 如果是当前选中的时刻，更新当前状态
        if (_currentMoment.value?.uniqueIdentifier == momentId) {
          _currentMoment.value = updatedMoment;
        }
      }

      _loadCommentsForMoment(momentId);
      _refreshAllMoments();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 删除评论
  bool deleteComment(String commentId) {
    try {
      final index = _commentList.indexWhere(
        (comment) => comment.uniqueIdentifier == commentId,
      );
      if (index != -1) {
        final comment = _commentList[index];
        _commentList.removeAt(index);

        // 更新对应风筝时刻的评论数量
        final momentIndex = _momentList.indexWhere(
          (moment) => moment.uniqueIdentifier == comment.momentIdentifier,
        );
        if (momentIndex != -1) {
          final updatedMoment = _momentList[momentIndex]
              .duplicateWithModifications(
                commentCount: _momentList[momentIndex].commentCount - 1,
              );
          _momentList[momentIndex] = updatedMoment;

          // 如果是当前选中的时刻，更新当前状态
          if (_currentMoment.value?.uniqueIdentifier ==
              comment.momentIdentifier) {
            _currentMoment.value = updatedMoment;
          }
        }

        // 刷新评论列表
        _loadCommentsForMoment(comment.momentIdentifier);
        _refreshAllMoments();
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 获取指定风筝时刻的评论列表
  List<KiteMomentCommentEntity> getCommentsForMoment(String momentId) {
    final comments =
        _commentList
            .where((comment) => comment.momentIdentifier == momentId)
            .toList();
    comments.sort((a, b) => a.publishTimestamp.compareTo(b.publishTimestamp));
    return comments;
  }

  /// 根据媒体类型筛选风筝时刻
  List<KiteMomentEntity> getMomentsByMediaType(MediaType mediaType) {
    return _momentList
        .where((moment) => moment.mediaType == mediaType)
        .toList();
  }

  /// 搜索风筝时刻（根据标题和内容）
  List<KiteMomentEntity> searchMoments(String keyword) {
    if (keyword.isEmpty) return getAllKiteMoments();

    final lowerKeyword = keyword.toLowerCase();
    return _momentList
        .where(
          (moment) =>
              moment.momentTitle.toLowerCase().contains(lowerKeyword) ||
              moment.contentText.toLowerCase().contains(lowerKeyword),
        )
        .toList();
  }

  /// 私有方法：加载指定风筝时刻的评论
  void _loadCommentsForMoment(String momentId) {
    final comments = getCommentsForMoment(momentId);
    _currentComments.value = comments;
  }

  /// 私有方法：刷新所有风筝时刻状态
  void _refreshAllMoments() {
    getAllKiteMoments(); // 这会更新 _allMoments 状态
  }

  /// 私有方法：刷新当前用户的风筝时刻状态
  void _refreshUserMoments() {
    // 获取当前用户ID
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser != null) {
      getUserKiteMoments(currentUser.uniqueIdentifier);
    }
  }

  /// 获取统计信息
  Map<String, int> getStatistics() {
    return {
      'totalMoments': _momentList.length,
      'imageMoments': getMomentsByMediaType(MediaType.image).length,
      'videoMoments': getMomentsByMediaType(MediaType.video).length,
      'totalComments': _commentList.length,
    };
  }
}
